import express from "express";
const app = express();

app.use((req, res, next) => {
  const { headers } = req;
  res.setHeader("Access-Control-Allow-Origin", headers.origin as string);
  next();
});

app.get("/cache-control", (_, res) => {
  res.setHeader("Cache-Control", "public, max-age=5");
  res.json("测试cache-control缓存");
});

app.get("/expires", (_, res) => {
  res.setHeader("Expires", new Date(Date.now() + 5 * 1000).toUTCString());
  res.json("测试Expires缓存");
});

app.get("/last-modified", (req, res) => {
  res.setHeader("Last-Modified", new Date().toUTCString());
  if (new Date(req.headers["if-modified-since"] ?? "").getTime() + 5 * 1000 > Date.now()) {
    console.log("协商缓存命中");
    res.statusCode = 304;
    return;
  }
  res.json("测试Last-Modified缓存");
});

app.listen(3002, () => {
  console.log("测试http缓存服务器正在启动http://localhost:3003");
});
